//
//  DateDesignViewController.m
//  lvtu
//
//  Created by Apple on 12-3-20.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "DateDesignViewController.h"
#import "DateDetailView.h"
#import "CustomTabBarController.h"
#import "NSDate+Helper.h"

@implementation DateDesignViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)dealloc
{
    [super dealloc];
}

#pragma mark - View lifecycle

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView
{
}
*/

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    [super viewDidLoad];
    [DataSource shareInstance].isEdit = NO;
//    self.navigationItem.title = @"旅途设计";
    UILabel* tempLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 44)];
    [tempLabel setText:@"旅途设计"];
    [tempLabel setBackgroundColor:[UIColor clearColor]];
    [tempLabel setTextAlignment:UITextAlignmentCenter];
    [tempLabel setTextColor:[UIColor colorWithRed:111/255.0 green:117/255.0 blue:81/255.0 alpha:1.0]];
    [tempLabel setFont:[UIFont boldSystemFontOfSize:20]];
    self.navigationItem.titleView = tempLabel;
    [tempLabel release];
    tempLabel = nil;
    
    dateIndex = 1;
    
    backgroundScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
    backgroundScrollView.backgroundColor = [UIColor clearColor];
    backgroundScrollView.contentSize = CGSizeMake(self.view.frame.size.width, self.view.frame.size.height+100);
    
    backgroundScrollView.pagingEnabled = NO;
    backgroundScrollView.scrollEnabled = NO;
    backgroundScrollView.clipsToBounds = YES;
    backgroundScrollView.scrollsToTop = YES;
    backgroundScrollView.showsVerticalScrollIndicator = NO;
    backgroundScrollView.showsHorizontalScrollIndicator = NO;
    backgroundScrollView.delegate = self;
    [self.view addSubview:backgroundScrollView];
    
    DateDetailView* dateDetailView = [[DateDetailView alloc] initWithFrame:CGRectMake(35, 80, 253, 23)];
    dateDetailView.dateLabel.text = @"第1天";
    dateDetailView.dateLabel.font = [UIFont systemFontOfSize:14];
    dateDetailView.dateLabel.backgroundColor = [UIColor clearColor];
    dateDetailView.detailLabel.text = @"选择第一天行程的时间";
    dateDetailView.detailLabel.font = [UIFont systemFontOfSize:12];
    dateDetailView.detailLabel.textColor = [UIColor colorWithRed:122/255.0 green:143/255.0 blue:68/255.0 alpha:1];
    dateDetailView.detailLabel.backgroundColor = [UIColor clearColor];
    [backgroundScrollView addSubview:dateDetailView];
    [dateDetailView release];
    
    UIImageView* dateInputView = [[UIImageView alloc] initWithFrame:CGRectMake(35, 105, 253, 40)];
    dateInputView.backgroundColor = [UIColor colorWithRed:227/255.0 green:227/255.0 blue:227/255.0 alpha:1.0];
    dateInputView.image = [UIImage imageNamed:@"bg_imput.png"];
    dateInputView.userInteractionEnabled = YES;
    [backgroundScrollView addSubview:dateInputView];
    [dateInputView release];
    
    dateShowLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 10, 140, 20)];
    dateShowLabel.backgroundColor = [UIColor clearColor];
    dateShowLabel.font = [UIFont boldSystemFontOfSize:22.0];
    dateShowLabel.textColor = [UIColor colorWithRed:255/255.0 green:85/255.0 blue:0/255.0 alpha:1.0];
    
    NSDate *today = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    dateShowLabel.text = [NSString stringWithFormat:@"%@",[dateFormatter stringFromDate:today]];
    [dateInputView addSubview:dateShowLabel];
    [dateFormatter release];
    
    UIButton* datebutton = [UIButton buttonWithType:UIButtonTypeCustom];
	datebutton.frame = CGRectMake(0, 0, 253, 40);
    [datebutton setBackgroundColor:[UIColor clearColor]];
	[datebutton addTarget:self action:@selector(dateSelectButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
	[dateInputView addSubview:datebutton];
    
    UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];
	button.frame = CGRectMake(220, 10, 20, 20);
    [button setBackgroundImage:[UIImage imageNamed:@"btn_unfold_normal.png"] forState:UIControlStateNormal];
    [button setBackgroundImage:[UIImage imageNamed:@"btn_unfold_press.png"] forState:UIControlStateHighlighted];
	[button addTarget:self action:@selector(dateSelectButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
	[dateInputView addSubview:button];
    
    UIButton* buttonNext = [UIButton buttonWithType:UIButtonTypeCustom];
	buttonNext.frame = CGRectMake(80, 180, 160, 40);
    [buttonNext setBackgroundImage:[UIImage imageNamed:@"btn_done_normal.png"] forState:UIControlStateNormal];
    [buttonNext setBackgroundImage:[UIImage imageNamed:@"btn_done_press.png"] forState:UIControlStateHighlighted];
	[buttonNext setTitle:@"下一步 >" forState:UIControlStateNormal];
    buttonNext.titleLabel.font = [UIFont boldSystemFontOfSize:16];
	[buttonNext addTarget:self action:@selector(nextButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
	[backgroundScrollView addSubview:buttonNext];
}

- (void)viewDidUnload
{
    [backgroundScrollView release];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
//    return (interfaceOrientation == UIInterfaceOrientationPortrait);
    return NO;
}

- (void)viewWillAppear:(BOOL)animated
{
    dateIndex = 1;
    [DataSource shareInstance].isEdit = NO;
}

- (void)dateChanged:(id)sender
{
    UIDatePicker* datePicker = (UIDatePicker*)sender;
    // report the selection to the UI label
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    dateShowLabel.text = [NSString stringWithFormat:@"%@",[dateFormatter stringFromDate:datePicker.date]];
    [dateFormatter release];
}

- (void)dateSelectButtonPressed:(id)sender
{
    if (backgroudImageView) {
        return;
    }
    backgroudImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 163, 320, 47)];
    backgroudImageView.image = [UIImage imageNamed:@"bg_system_title.png"];
    backgroudImageView.userInteractionEnabled = YES;
    [self.view addSubview:backgroudImageView];
    
    UIButton* okbutton = [UIButton buttonWithType:UIButtonTypeCustom];
	okbutton.frame = CGRectMake(245, 8, 68, 34);
    [okbutton setBackgroundImage:[UIImage imageNamed:@"btn_system_normal.png"] forState:UIControlStateNormal];
    [okbutton setBackgroundImage:[UIImage imageNamed:@"btn_system_press.png"] forState:UIControlStateHighlighted];
	[okbutton setTitle:@"确定" forState:UIControlStateNormal];
    okbutton.titleLabel.font = [UIFont systemFontOfSize:14.0];
	[okbutton addTarget:self action:@selector(okButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
	[backgroudImageView addSubview:okbutton];
    
    UIButton* cancelButton = [UIButton buttonWithType:UIButtonTypeCustom];
	cancelButton.frame = CGRectMake(10, 8, 68, 34);
    [cancelButton setBackgroundImage:[UIImage imageNamed:@"btn_system_normal.png"] forState:UIControlStateNormal];
    [cancelButton setBackgroundImage:[UIImage imageNamed:@"btn_system_press.png"] forState:UIControlStateHighlighted];
	[cancelButton setTitle:@"取消" forState:UIControlStateNormal];
    cancelButton.titleLabel.font = [UIFont systemFontOfSize:14.0];
	[cancelButton addTarget:self action:@selector(cancelButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
	[backgroudImageView addSubview:cancelButton];
    
    datePickerView = [[UIDatePicker alloc] initWithFrame:CGRectZero];
	datePickerView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
	datePickerView.datePickerMode = UIDatePickerModeDate;
	
	// note we are using CGRectZero for the dimensions of our picker view,
	// this is because picker views have a built in optimum size,
	// you just need to set the correct origin in your view.
	//
	// position the picker at the bottom
	datePickerView.frame = CGRectMake(0.0,210,320,200);
	
	// add this picker to our view controller, initially hidden
	datePickerView.hidden = NO;
    NSDate *today = [NSDate date];
    [datePickerView addTarget:self action:@selector(dateChanged:) forControlEvents:UIControlEventValueChanged];
	datePickerView.date = today;
	[self.view addSubview:datePickerView];
    
    [backgroundScrollView setContentOffset:CGPointMake(0, 20) animated:YES]; 
}

- (void)okButtonPressed:(id)sender
{
    if (!backgroudImageView) {
        return;
    }
    if ([backgroudImageView isDescendantOfView:self.view]) {
        [backgroudImageView removeFromSuperview];
        [backgroudImageView release];backgroudImageView = nil;
    }
    if ([datePickerView isDescendantOfView:self.view]) {
        [datePickerView removeFromSuperview];
        [datePickerView release];datePickerView = nil;
    }
    [backgroundScrollView setContentOffset:CGPointMake(0, 0) animated:YES];
}

- (void)cancelButtonPressed:(id)sender
{
    if (!backgroudImageView) {
        return;
    }
    if ([backgroudImageView isDescendantOfView:self.view]) {
        [backgroudImageView removeFromSuperview];
        [backgroudImageView release];backgroudImageView = nil;
    }
    if ([datePickerView isDescendantOfView:self.view]) {
        [datePickerView removeFromSuperview];
        [datePickerView release];datePickerView = nil;
    }
    NSDate *today = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    dateShowLabel.text = [NSString stringWithFormat:@"%@",[dateFormatter stringFromDate:today]];
    [backgroundScrollView setContentOffset:CGPointMake(0, 0) animated:YES];
    [dateFormatter release];
}

- (void)nextButtonPressed:(id)sender
{
//    [[DataSource shareInstance] creatNewDate:dateShowLabel.text];
//    DateEventViewController* dateEventViewController = [[DateEventViewController alloc] init];
//    [dateEventViewController setDateContent:[NSString stringWithFormat:@"第%d天",dateNum] date:dateShowLabel.text];
//    dateEventViewController.delegate = self;
//    //CustomTabBarController* tabarController = (CustomTabBarController*)self.tabBarController;
//    [self.navigationController pushViewController:dateEventViewController animated:YES];
//    //[dateEventViewController release];
    
    NSArray* keyArray = [[DataSource shareInstance].creatTripInfo.datedic allKeys];
    BOOL isFind = NO;
    for (NSString* key in keyArray) {
        if ([key isEqualToString:dateShowLabel.text]) {
            isFind = YES;
            break;
        }
    }
    if (isFind) {
        [[DataSource shareInstance] setDate:dateShowLabel.text];
    }
    else{
        
        [[DataSource shareInstance] creatNextDate:dateShowLabel.text];
    }
    eventEditController = [[EventEditViewController alloc] init];
    [eventEditController setCurrentInfo:dateIndex];
    eventEditController.delegate = self;
    [self.navigationController pushViewController:eventEditController animated:YES];
    [eventEditController release];
}

- (void)touchPreDayButton
{
    dateIndex--;
    NSDate* date = [NSDate dateWithDateString:dateShowLabel.text] ;
    NSTimeInterval timeInterval = [date timeIntervalSinceReferenceDate];
    timeInterval += 24*60*60*(dateIndex-1);
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    date = [NSDate dateWithTimeIntervalSinceReferenceDate:timeInterval];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString* dateString = [NSString stringWithFormat:@"%@",[dateFormatter stringFromDate:date]];
    [dateFormatter release];
    
    [eventEditController.navigationController popViewControllerAnimated:NO];
    [[DataSource shareInstance] setDate:dateString];
    
    NSArray* eventArray = [[DataSource shareInstance] getCurrentEvent];
    for (PlaceInfo* info in eventArray) {
        for (CityInfo* city in [DataSource shareInstance].cityArray) {
            if ([info.cityid isEqualToString:city.cityid]) {
                [DataSource shareInstance].defaultCityInfo = city;
                break;
            }
        }
        break;
    }
    
    eventEditController = [[EventEditViewController alloc] init];
    [eventEditController setCurrentInfo:dateIndex];
    eventEditController.delegate = self;
    
    CATransition *transition = [CATransition animation];
    transition.duration = 0.2;
//    transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
    transition.type = kCATransitionPush;
    transition.subtype = kCATransitionFromLeft;
    transition.delegate = self;
    self.navigationController.navigationBarHidden = NO;
    [self.navigationController pushViewController:eventEditController animated:NO];
    [self.navigationController.view.layer addAnimation:transition forKey:nil];
    
    [eventEditController release];
}

- (void)touchNextDayButton
{
    if ([[[DataSource shareInstance] getCurrentEvent] count] == 0) {
        UIAlertView* baseAlert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"今天还未添加任何内容哟~" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [baseAlert show];
        [baseAlert release];
        return;
    }
    dateIndex++;
    NSDate* date = [NSDate dateWithDateString:dateShowLabel.text] ;
    NSTimeInterval timeInterval = [date timeIntervalSinceReferenceDate];
    timeInterval += 24*60*60*(dateIndex-1);
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    date = [NSDate dateWithTimeIntervalSinceReferenceDate:timeInterval];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString* dateString = [NSString stringWithFormat:@"%@",[dateFormatter stringFromDate:date]];
    [dateFormatter release];
    
    [eventEditController.navigationController popViewControllerAnimated:NO];
    NSArray* keyArray = [[DataSource shareInstance].creatTripInfo.datedic allKeys];
    BOOL isFind = NO;
    for (NSString* key in keyArray) {
        if ([key isEqualToString:dateString]) {
            isFind = YES;
            break;
        }
    }
    if (isFind) {
        [[DataSource shareInstance] setDate:dateString];
    }
    else{
        
        [[DataSource shareInstance] creatNextDate:dateString];
    }
    
    NSArray* eventArray = [[DataSource shareInstance] getCurrentEvent];
    for (PlaceInfo* info in eventArray) {
        for (CityInfo* city in [DataSource shareInstance].cityArray) {
            if ([info.cityid isEqualToString:city.cityid]) {
                [DataSource shareInstance].defaultCityInfo = city;
                break;
            }
        }
        break;
    }
    
    eventEditController = [[EventEditViewController alloc] init];
    [eventEditController setCurrentInfo:dateIndex];
    eventEditController.delegate = self;
    [self.navigationController pushViewController:eventEditController animated:YES];
    [eventEditController release];
//    DateEventViewController* dateEventViewController = [[DateEventViewController alloc] init];
//    [dateEventViewController setDateContent:[NSString stringWithFormat:@"第%d天",dateNum] date:dateString];
//    dateEventViewController.delegate = self;
//    //CustomTabBarController* tabarController = (CustomTabBarController*)self.tabBarController;
//    [self.navigationController pushViewController:dateEventViewController animated:YES];
}

@end
